<template>
  <div class="feature-version__container">
    <div class="table-panel">
      <resource-table
        ref="refResourceTable"
        v-loading="ifLoading"
        :table-columns="tableColumns"
        :showSelection="true"
        operations="edit,delete"
        :operation-column-width="120"
        @queryTable="getList"
        @selectionChange="rowSelectionChange"
      >
        <template #headerLeft>
          <div class="btn-list">
            <div class="btn-item btn-add" style="width: 100px">
              <el-button v-waves type="primary" style="width: 100px" @click="handlerAddNew">
                新增
              </el-button>
            </div>
            <div class="btn-item btn-add-batch" style="width: 100px; margin-left: 10px">
              <el-button v-waves type="primary" style="width: 100px" @click="handlerImportData">
                导入
              </el-button>
            </div>
            <div
              v-show="rowsSelected.length > 1"
              class="btn-item btn-delete-batch"
              style="width: 100px; margin-left: 10px"
            >
              <el-button v-waves type="danger" style="width: 100px" @click="handlerDeleteBatch">
                批量删除
              </el-button>
            </div>
          </div>
        </template>
        <template #headerRight="props">
          <div class="filter-conditions">
            <!-- <div class="filter-item">
              申请时间：
              <el-date-picker
                v-model="props.queryParameters.timeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handlerClear"
              >
              </el-date-picker>
            </div>-->
            <div class="filter-item" style="margin-left: 10px">
              业务类型：
              <el-input
                placeholder="请输入业务类型"
                size="small"
                style="width: 170px"
                v-model="props.queryParameters.businessType"
                clearable
                @keyup.native="() => handlerInputValueChange('businessType')"
                @clear="() => handlerClear('businessType')"
              >
              </el-input>
              <!-- <el-select
                v-model="props.queryParameters.businessType"
                size="small"
                style="width: 170px"
                placeholder="请输入业务类型"
                clearable
                @clear="handlerClear"
              >
                <el-option
                  v-for="item in businessTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select> -->
            </div>
            <div class="filter-item" style="margin-left: 10px">
              要素名称：
              <el-input
                placeholder="请输入要素名称"
                size="small"
                style="width: 170px"
                v-model="props.queryParameters.featureCName"
                clearable
                @keyup.native="() => handlerInputValueChange('featureCName')"
                @clear="() => handlerClear('featureCName')"
              >
              </el-input>
              <!-- <el-select
                v-model="props.queryParameters.featureName"
                size="small"
                style="width: 170px"
                placeholder="请输入要素名称"
                clearable
                @clear="handlerClear"
              >
                <el-option
                  v-for="item in featureNameOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select> -->
            </div>
            <div class="filter-item" style="margin-left: 10px">
              版本名称：
              <el-input
                placeholder="请输入版本名称"
                size="small"
                style="width: 170px"
                v-model="props.queryParameters.versionCName"
                clearable
                @keyup.native="() => handlerInputValueChange('versionCName')"
                @clear="() => handlerClear('versionCName')"
              >
              </el-input>
              <!-- <el-select
                v-model="props.queryParameters.featureVersion"
                size="small"
                style="width: 170px"
                placeholder="请输入要素版本"
                clearable
                @clear="handlerClear"
              >
                <el-option
                  v-for="item in featureVersionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select> -->
            </div>
            <!-- <div class="filter-item" style="margin-left: 10px">
              字段名称：
              <el-select
                v-model="props.queryParameters.fieldName"
                size="small"
                style="width: 170px"
                placeholder="请输入字段名称"
                clearable
                @clear="handlerClear"
              >
                <el-option
                  v-for="item in fieldNameOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div> -->
          </div>
        </template>
        <template #operation="props">
          <el-tooltip
            v-if="props.rowInfo.canEnum === '是'"
            class="col-btn-icon"
            effect="dark"
            content="值域配置"
            placement="top"
          >
            <el-button
              type="text"
              size="mini"
              icon="el-icon-notebook-2"
              @click="handlerFieldDomainManage(props.rowInfo)"
              style="font-size: 15px; color: #409eff"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip class="col-btn-icon" effect="dark" content="修改" placement="top">
            <el-button
              type="text"
              @click="handlerModify(props.rowInfo)"
              icon="el-icon-edit"
              style="font-size: 15px; color: #67c23a"
            ></el-button>
          </el-tooltip>
          <el-tooltip class="col-btn-icon" effect="dark" content="删除" placement="top">
            <el-button
              type="text"
              @click="handlerDelete(props.rowInfo)"
              icon="el-icon-delete"
              style="font-size: 15px; color: #f56c6c"
            ></el-button>
          </el-tooltip>
          <!-- <el-tooltip class="col-btn-icon" effect="dark" content="所在图层" placement="top">
            <el-button
              type="text"
              size="mini"
              icon="el-icon-copy-document"
              @click="handlerLayerManage(props.rowInfo)"
              style="font-size: 15px; color: #409eff"
            >
            </el-button>
          </el-tooltip> -->
          <el-tooltip class="col-btn-icon" effect="dark" content="数据标准版本" placement="top">
            <el-button
              type="text"
              size="mini"
              icon="el-icon-s-management"
              @click="handlerFeatureVersionManage(props.rowInfo)"
              style="font-size: 15px; color: #409eff"
            >
            </el-button>
          </el-tooltip>
        </template>
      </resource-table>
    </div>
    <!-- 数据库信息窗口 -->
    <el-dialog
      :title="formDialogTitle"
      :center="true"
      :visible.sync="formDialogVisible"
      :close-on-click-modal="false"
      class="form-dialog"
      width="40%"
      height="40%"
    >
      <el-form :ref="refFormName" :model="form" :rules="formRules" label-width="80px">
        <el-form-item label-width="0">
          <el-col :span="12">
            <el-form-item label="要素版本" prop="featureVersion">
              <el-select
                v-model="form.featureVersion"
                placeholder="请选择要素版本"
                class="form-item"
                remote
                filterable
                :remote-method="remoteGetVersionsOptions"
                @change="handlerVersionChange"
              >
                <el-option
                  v-for="item in featureVersionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段出处" prop="docStandard">
              <el-select
                v-model="form.docStandard"
                placeholder="请选择字段出处"
                class="form-item"
                clearable
              >
                <el-option
                  v-for="item in docStandardOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label-width="0">
          <el-col :span="12">
            <el-form-item label="字段名" prop="name">
              <el-input v-model="form.name" placeholder="请输入字段名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段别名" prop="alias">
              <el-input v-model="form.alias" placeholder="请输入字段别名"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label-width="0">
          <el-col :span="12">
            <el-form-item label="字段类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择字段类型" class="form-item">
                <el-option
                  v-for="item in fieldTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段顺序" prop="order">
              <el-input
                v-model="form.order"
                placeholder="请输入字段顺序"
                @keyup.native="
                  (e) => {
                    checkIFNum('order', form.order);
                  }
                "
              ></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label-width="0">
          <el-col :span="12">
            <el-form-item label="字段长度" prop="length">
              <el-input
                v-model="form.length"
                placeholder="请输入字段长度"
                @keyup.native="
                  (e) => {
                    checkIFNum('length', form.length);
                  }
                "
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段精度" prop="precision">
              <el-input
                v-model="form.precision"
                placeholder="请输入字段精度"
                @keyup.native="
                  (e) => {
                    checkIFNum('precision', form.precision);
                  }
                "
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label-width="0">
          <el-col :span="3">&nbsp;</el-col>
          <el-col :span="9">
            <el-form-item label="字段值是否可为空" prop="nullable" label-width="150">
              <el-radio-group v-model="form.nullable">
                <el-radio label="是"></el-radio>
                <el-radio label="否"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label-width="0">
          <el-col :span="3">&nbsp;</el-col>
          <el-col :span="9">
            <el-form-item label="字段值是否不重复" prop="isUnique" label-width="150">
              <el-radio-group v-model="form.isUnique">
                <el-radio label="是"></el-radio>
                <el-radio label="否"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label-width="0">
          <el-col :span="3">&nbsp;</el-col>
          <el-col :span="9">
            <el-form-item label="字段值是否可枚举" prop="canEnum" label-width="150">
              <el-radio-group v-model="form.canEnum">
                <el-radio label="是"></el-radio>
                <el-radio label="否"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-form-item>

        <!-- <el-form-item label="是否为标准字段" prop="isStandard">
          <el-radio-group v-model="form.isStandard">
            <el-radio label="是"></el-radio>
            <el-radio label="否"></el-radio>
          </el-radio-group>
        </el-form-item> -->

        <el-form-item label="备注" prop="desc">
          <el-input
            v-model="form.desc"
            type="textarea"
            placeholder="请输入备注"
            :rows="4"
          ></el-input>
        </el-form-item>
        <el-form-item label-width="0">
          <div style="width: 100%; text-align: center">
            <el-button type="primary" @click="handlerSubmit(refFormName)">确定</el-button>
            <el-button @click="handlerCancel(refFormName)">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 上传组件 -->
    <div class="upload-container" v-show="false">
      <el-upload
        :ref="refUploadFile"
        class="upload-demo"
        :action="upload.url"
        :limit="upload.limit"
        :accept="upload.accept"
        :file-list="upload.fileList"
        :before-remove="uploadFileBeforeRemove"
        :on-remove="uploadFileRemove"
        :on-exceed="uploadFileExceed"
        :before-upload="uploadBeforeFile"
        :on-success="uploadFileSuccess"
        :on-change="uploadFileStateChange"
        :http-request="httpUpload"
      >
        <el-button ref="refUploadButton" size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传 .excel 文件，且不超过 {{ upload.maxFielSize_M }}M
        </div>
      </el-upload>
    </div>
  </div>
</template>

<script>
import * as moment from 'moment';
import waves from '@/directive/waves';
import { pageList, addOne, updateOne, deleteOne, importBatchData } from '@/api/data-standard/field';
import { pageList as dictEnumList } from '@/api/data-standard/dictEnum';
import { pageList as versionList } from '@/api/data-standard/featureVersion';
import { pageList as standardDocsList } from '@/api/data-standard/standardDocs';
import { pageList as domainList } from '@/api/data-standard/fieldDomain';

export default {
  name: 'FeatureVersion',
  components: {},
  directives: {
    waves,
  },
  data() {
    return {
      // 表格这遮罩
      ifLoading: false,
      // 业务类型
      // businessTypeOptions: [
      //   {
      //     label: '常规监测',
      //     value: 'CGJC',
      //   },
      //   {
      //     label: '督察执法',
      //     value: 'DCZF',
      //   },
      //   {
      //     label: '用地审批',
      //     value: 'YDSP',
      //   },
      //   {
      //     label: '现状调查',
      //     value: 'XZDC',
      //   },
      // ],
      // // 要素名称
      // featureNameOptions: [
      //   {
      //     label: '常规监测图斑',
      //     value: 'CGJCTB',
      //     pId: 'CGJC',
      //   },
      //   {
      //     label: '卫片执法国家下发图斑',
      //     value: 'WPZF_GJXFTB',
      //     pId: 'DCZF',
      //   },
      //   {
      //     label: '中间征地',
      //     value: 'TDZS_ZJK',
      //     pId: 'YDSP',
      //   },
      //   {
      //     label: '成果征地',
      //     value: 'TDZS_CGK',
      //     pId: 'YDSP',
      //   },
      //   {
      //     label: '地类图斑',
      //     value: 'DLTB',
      //     pId: 'XZDC',
      //   },
      // ],
      // 要素版本
      featureVersionOptions: [
        // {
        //   label: '二调地类图斑',
        //   value: '64309174-011a-11ee-8147-080058000005',
        //   id: '64309174-011a-11ee-8147-080058000005',
        //   versionName: 'DLTB_ED',
        //   versionCName: '二调地类图斑',
        //   versionSerial: 1,
        //   featureId: 'c9abd67f-5587-4a8e-b655-77e90d3a9e3c',
        // },
        // {
        //   label: '三调地类图斑',
        //   value: '79e5250c-011a-11ee-8148-080058000005',
        //   id: '79e5250c-011a-11ee-8148-080058000005',
        //   versionName: 'DLTB_SD',
        //   versionCName: '三调地类图斑',
        //   versionSerial: 2,
        //   featureId: 'c9abd67f-5587-4a8e-b655-77e90d3a9e3c',
        // },
      ],
      // 字段名称
      fieldNameOptions: [
        {
          label: '标识码',
          value: 'bsm',
        },
        {
          label: '地类编码',
          value: 'dlbm',
        },
        {
          label: '地类名称',
          value: 'dlmc',
        },
        {
          label: '图斑面积',
          value: 'tbmj',
        },
      ],
      // 标准文档
      docStandardOptions: [
        // {
        //   label: '《第三次全国土地调查技术规程》',
        //   value: '1',
        // },
        // {
        //   label: '《2020国土变更调查技术规程》',
        //   value: '2',
        // },
        // {
        //   label: '《第二次全国土地调查技术规程》',
        //   value: '3',
        // },
      ],
      // 字段类型
      fieldTypeOptions: [
        // {
        //   label: '固定长度文本',
        //   value: 'CHAR',
        // },
        // {
        //   label: '可变长度文本',
        //   value: 'VARCHAR',
        // },
        // {
        //   label: '短整型',
        //   value: 'SHORT_INT',
        // },
        // {
        //   label: '整型',
        //   value: 'INT',
        // },
        // {
        //   label: '长整型',
        //   value: 'LONG',
        // },
        // {
        //   label: '单精度浮点型',
        //   value: 'FLOAT',
        // },
        // {
        //   label: '双精度浮点型',
        //   value: 'DOUBLE',
        // },
        // {
        //   label: '日期类型',
        //   value: 'DATETIME',
        // },
        // {
        //   label: '时间戳',
        //   value: 'TIMESTAMP',
        // },
      ],
      // 表格列配置
      tableColumns: [
        {
          key: 0,
          prop: 'id',
          align: 'center',
          label: '唯一标识',
          width: '140',
        },
        {
          key: 1,
          prop: 'name',
          align: 'center',
          label: '字段名',
          width: '80',
        },
        {
          key: 2,
          prop: 'alias',
          align: 'center',
          label: '字段别名',
          width: '100',
        },
        {
          key: 3,
          prop: 'type',
          align: 'center',
          label: '字段类型',
          width: '100',
        },
        {
          key: 4,
          prop: 'order',
          align: 'center',
          label: '字段顺序',
          width: '70',
        },
        {
          key: 5,
          prop: 'length',
          align: 'center',
          label: '字段长度',
          width: '70',
        },
        {
          key: 6,
          prop: 'precision',
          align: 'center',
          label: '字段精度',
          width: '70',
        },
        {
          key: 7,
          prop: 'nullable',
          align: 'center',
          label: '是否可为空值',
          width: '64',
        },
        {
          key: 8,
          prop: 'isUnique',
          align: 'center',
          label: '是否取值不重复',
          width: '70',
        },
        {
          key: 9,
          prop: 'isStandard',
          align: 'center',
          label: '是否为标准化字段',
          width: '70',
        },
        {
          key: 10,
          prop: 'canEnum',
          align: 'center',
          label: '是否值域可枚举',
          width: '70',
        },
        {
          key: 11,
          prop: 'businessType',
          align: 'center',
          label: '业务类型',
          width: '100',
        },
        {
          key: 12,
          prop: 'featureName',
          align: 'center',
          label: '要素名称',
          width: '100',
        },
        {
          key: 13,
          prop: 'featureVersion',
          align: 'center',
          label: '要素版本',
          width: '100',
        },
        {
          key: 14,
          prop: 'desc',
          align: 'center',
          label: '备注',
          minWidth: '120',
        },
      ],
      // 表格数据
      tableData: [],
      // 表格选中行
      rowsSelected: [],
      // 表单ref
      refFormName: 'dbForm',
      // 表单标题
      formDialogTitle: '',
      // 表单显隐
      formDialogVisible: false,
      // 默认的表单数据
      defaultForm: {
        id: null,
        featureVersion: '',
        docStandard: '',
        name: '',
        alias: '',
        type: '',
        order: null,
        length: null,
        precision: null,
        nullable: '否',
        isUnique: '否',
        isStandard: '是',
        canEnum: '否',
        desc: '',
      },
      // 表单数据
      form: {
        id: null,
        featureVersion: '',
        docStandard: '',
        name: '',
        alias: '',
        type: '',
        order: null,
        length: null,
        precision: null,
        nullable: '否',
        isUnique: '否',
        isStandard: '是',
        canEnum: '否',
        desc: '',
      },
      // 表单校验规则
      formRules: {
        featureVersion: [{ required: true, message: '请输入要素版本', trigger: 'blur' }],
        // docStandard: [{ required: true, message: '请选择字段出处', trigger: 'blur' }],
        name: [{ required: true, message: '请输入字段名', trigger: 'blur' }],
        alias: [{ required: true, message: '请输入字段别名', trigger: 'blur' }],
        type: [{ required: true, message: '请选择字段类型', trigger: 'blur' }],
        order: [{ required: true, message: '请选择字段顺序', trigger: 'blur' }],
        length: [{ required: true, message: '请输入字段长度', trigger: 'blur' }],
        nullable: [{ required: true, message: '请选择字段取值是否可为空值', trigger: 'change' }],
        isUnique: [{ required: true, message: '请选择字段取值是否不重复', trigger: 'change' }],
        isStandard: [
          { required: true, message: '请输入字段是否为来自标准文档', trigger: 'change' },
        ],
        canEnum: [{ required: true, message: '请选择字段取值是否可枚举', trigger: 'change' }],
      },
      // 文件上传组件参数
      refUploadFile: 'refUploadFile',
      upload: {
        url: '', // excel文件上传路径
        // disabled: false, // 上传组件是否可用-永不启用，为true的时候，已上传的文件无法删除
        accept: '.xlsx,.xls',
        limit: 1, // 上传的最大文件个数限制
        maxFielSize_M: 1, // 单个文件的限制大小（单位：M）
        fileList: [], // 上传的文件列表
      },
    };
  },
  beforeMount() {
    this.preInit();
  },
  mounted() {},
  methods: {
    preInit() {
      const vm = this;
      // 初始化字段类型
      dictEnumList({
        query: {
          page: 1,
          pageSize: 500,
        },
        data: {
          typeName: '字段类型',
        },
      })
        .then((res) => {
          if (res.status === 'success') {
            const {
              data: { items },
            } = res;
            vm.fieldTypeOptions = items.map((item) => {
              const { id, typeCode, typeName, dictKey, dictValue } = item;
              return {
                id: id,
                label: dictValue,
                value: dictValue,
                typeCode: typeCode,
                typeName: typeName,
                dictKey: dictKey,
                dictValue: dictValue,
              };
            });
          } else {
            vm.$message.error(res.message);
          }
        })
        .catch((err) => {
          throw err;
        });
    },
    /**
     * 获取表格数据
     */
    getList(queryParameters, callback) {
      const vm = this;
      if (JSON.stringify(vm.$route.query) !== '{}') {
        const refTable = vm.getRefDom('refResourceTable');
        if (refTable && vm.$route.query.hasOwnProperty('businessType')) {
          vm.runtimeSet(
            refTable,
            refTable.queryParameters,
            'businessType',
            vm.$route.query.businessType,
          );
        }
        if (refTable && vm.$route.query.hasOwnProperty('featureCName')) {
          vm.runtimeSet(
            refTable,
            refTable.queryParameters,
            'featureCName',
            vm.$route.query.featureCName,
          );
        }
        if (refTable && vm.$route.query.hasOwnProperty('versionCName')) {
          vm.runtimeSet(
            refTable,
            refTable.queryParameters,
            'versionCName',
            vm.$route.query.versionCName,
          );
        }
      }
      const { businessType, featureCName, versionCName, pageSize, page } = queryParameters;
      pageList({
        query: {
          page: page,
          pageSize: pageSize,
        },
        data: {
          // id:data.id,
          // versionName:data.versionName,
          versionCName: !versionCName ? null : versionCName.trim(),
          // versionSerial:data.versionSerial,
          // versionDesc:data.versionDesc,
          // featureId:data.featureId,
          // createTime:data.createTime,
          // updateTime:data.updateTime,
          // isDeleted:data.isDeleted,
          // featureName:data.featureName,
          featureCName: !featureCName ? null : featureCName.trim(),
          // isGeometry:data.isGeometry,
          // geometryType:data.geometryType,
          businessType: !businessType ? null : businessType.trim(),
          // updateMethod:data.updateMethod,
          // updateRate:data.updateRate,
          // featureDesc:data.featureDesc,
        },
      })
        .then((res) => {
          if (res.status === 'success') {
            vm.ifLoading = false;
            const {
              data: { items, total },
            } = res;
            const tableData = items.map((item, index) => {
              const {
                id,
                fieldName,
                fieldAlias,
                fieldType,
                fieldLength,
                fieldPrecision,
                isNullable,
                isUnique,
                standardDocId,
                isStandard,
                canEnum,
                fieldOrder,
                fieldDesc,
                featureVersionId,
                createTime,
                updateTime,
                isDeleted,
                versionName,
                versionCName,
                versionSerial,
                featureId,
                featureName,
                featureCName,
                isGeometry,
                geometryType,
                businessType,
                updateMethod,
                updateRate,
              } = item;
              return {
                id: id,
                name: fieldName,
                alias: fieldAlias,
                type: fieldType,
                order: fieldOrder,
                length: fieldLength,
                precision: fieldPrecision,
                nullable: vm.parseBool2Text(isNullable),
                isUnique: vm.parseBool2Text(isUnique),
                isStandard: vm.parseBool2Text(isStandard),
                canEnum: vm.parseBool2Text(canEnum),
                businessType: businessType,
                featureName: featureCName,
                featureVersion: versionCName,
                docStandard: standardDocId,
                desc: fieldDesc,
                featureVersionId: featureVersionId,
                featureId: featureId,
              };
            });
            const dataTotalCount = total;
            callback({
              items: tableData,
              total: dataTotalCount,
            });
          } else {
            vm.$message({
              type: 'error',
              message: res.message,
            });
          }
        })
        .catch((err) => {
          throw err;
        });
    },
    /**
     * 查询
     */
    handlerQuery() {
      const vm = this;
      const refResourceTable = vm.getRefDom('refResourceTable');
      if (refResourceTable) {
        refResourceTable.queryTable();
      }
    },
    /**
     * 导入
     */
    handlerAddBatch() {
      const vm = this;
    },
    /**
     * 添加数据
     */
    handlerAddNew() {
      const vm = this;
      vm.formDialogTitle = '新增要素字段配置';
      vm.resetFormFields();
      vm.form.docStandard = '';
      vm.docStandardOptions = [];
      vm.formDialogVisible = true;
    },
    /**
     * 修改数据
     */
    async handlerModify(row) {
      const vm = this;
      vm.formDialogTitle = '修改要素字段配置';
      vm.resetFormFields();
      // 要素版本
      const resVersions = await versionList({
        query: {
          page: 1,
          pageSize: 500,
        },
        data: {
          versionCName: row.featureVersion.trim(),
        },
      });
      if (resVersions.status === 'success') {
        vm.featureVersionOptions = resVersions.data.items.map((item) => {
          const {
            id,
            versionName,
            versionCName,
            versionSerial,
            isLatestVersion,
            versionDesc,
            featureId,
            createTime,
            updateTime,
            isDeleted,
            featureName,
            featureCName,
            isGeometry,
            geometryType,
            businessType,
            updateMethod,
            updateRate,
            featureDesc,
          } = item;
          return {
            id: id,
            label: versionCName,
            value: id,
            versionName: versionName,
            versionCName: versionCName,
            versionSerial: versionSerial,
            featureId: featureId,
          };
        });
        // 规范、标准文档
        standardDocsList({
          query: {
            page: 1,
            pageSize: 1000000,
          },
          data: {
            versionCName: row.featureVersion.trim(),
          },
        })
          .then((res) => {
            if (res.status === 'success') {
              const {
                data: { items },
              } = res;
              vm.docStandardOptions = items.map((item) => {
                const { id, docName, filePath, docStandardType, docDesc } = item;
                return {
                  label: docName,
                  value: id,
                  id: id,
                  name: docName,
                  standardType: docStandardType,
                  path: filePath,
                  desc: docDesc,
                };
              });
              vm.form = {
                id: row.id,
                featureVersion: row.featureVersionId,
                docStandard: row.docStandard,
                name: row.name,
                alias: row.alias,
                type: row.type,
                order: row.order,
                length: row.length,
                precision: row.precision,
                nullable: row.nullable,
                isUnique: row.isUnique,
                isStandard: row.isStandard,
                canEnum: row.canEnum,
                desc: row.desc,
              };
              vm.formDialogVisible = true;
            } else {
              vm.$message({
                type: 'error',
                message: res.message,
              });
            }
          })
          .catch((err) => {
            throw err;
          });
      } else {
        vm.$message.error(res.message);
      }
    },
    /**
     * 删除数据
     */
    async handlerDelete(row) {
      const vm = this;
      const resData = await domainList({
        query: {
          page: 1,
          pageSize: 10,
        },
        data: {
          businessType: !row.businessType ? null : row.businessType.trim(),
          versionCName: !row.featureVersion ? null : row.featureVersion.trim(),
          featureCName: !row.featureName ? null : row.featureName.trim(),
          fieldAlias: !row.alias ? null : row.alias.trim(),
        },
      });
      if (resData.status === 'success') {
        if (resData.data && resData.data.total && resData.data.total > 0) {
          vm.$message.warning('当前要素仍关联至少一个取值，请先删除关联数据');
          return;
        }
      } else {
        vm.$message.error(resData.message);
        return;
      }

      vm.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteOne({
            query: {
              id: row.id,
            },
          })
            .then((res) => {
              if (res.status === 'success') {
                vm.$message({
                  type: 'success',
                  message: '删除成功!',
                });
                vm.handlerQuery();
              } else {
                vm.$message({
                  type: 'error',
                  message: res.message,
                });
              }
            })
            .catch((err) => {
              throw err;
            });
        })
        .catch(() => {
          vm.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    /**
     * 批量删除
     */
    handlerDeleteBatch() {
      const vm = this;
      const rows = vm.rowsSelected;
      vm.$confirm('此操作将永久删除所选的多条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          vm.$message({
            type: 'success',
            message: '删除成功!',
          });
          vm.handlerQuery();
        })
        .catch(() => {
          vm.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    /**
     * 取消提交
     */
    handlerCancel() {
      const vm = this;
      vm.dialogClose();
    },
    /**
     * 提交审批信息
     */
    handlerSubmit(formName) {
      const vm = this;
      vm.$refs[formName].validate((valid) => {
        if (valid) {
          const {
            id,
            featureVersion,
            docStandard,
            name,
            alias,
            type,
            order,
            length,
            precision,
            nullable,
            isUnique,
            isStandard,
            canEnum,
            desc,
          } = vm.form;
          const newFeature = {
            id: id,
            fieldName: name,
            fieldAlias: alias,
            fieldType: type,
            fieldLength: Number(length),
            fieldPrecision: Number(precision),
            isNullable: vm.parseText2Bool(nullable),
            isUnique: vm.parseText2Bool(isUnique),
            standardDocId: !docStandard ? null : docStandard,
            isStandard: vm.parseText2Bool(docStandard ? '是' : '否'),
            canEnum: vm.parseText2Bool(canEnum),
            fieldOrder: Number(order),
            fieldDesc: desc,
            featureVersionId: featureVersion,
          };
          if (id === null) {
            newFeature.id = null;
            addOne({
              query: {},
              data: newFeature,
            })
              .then((res) => {
                if (res.status === 'success') {
                  // 新增
                  vm.$message.success('新增成功');
                  vm.dialogClose();
                } else {
                  vm.$message({
                    type: 'error',
                    message: res.message,
                  });
                }
              })
              .catch((err) => {
                throw err;
              });
          } else {
            // 修改
            updateOne({
              query: {},
              data: newFeature,
            })
              .then((res) => {
                if (res.status === 'success') {
                  vm.$message.success('修改成功');
                  vm.dialogClose();
                } else {
                  vm.$message({
                    type: 'error',
                    message: res.message,
                  });
                }
              })
              .catch((err) => {
                throw err;
              });
          }
        } else {
          vm.$message.error('请正确填写表单项');
          return false;
        }
      });
    },
    /**
     * 导入
     */
    handlerImportData() {
      const vm = this;
      const domUploadButton = vm.$refs.refUploadButton.$el;
      // 清除当前文件上传组件的文件列表
      const refUploadFile = vm.$refs[vm.refUploadFile];
      if (refUploadFile && domUploadButton) {
        vm.$nextTick(() => {
          refUploadFile.clearFiles();
          vm.upload.accept = '.xlsx,.xls';
          vm.$nextTick(() => {
            domUploadButton.click();
          });
        });
      } else {
        vm.$message.error('上传组件失效，请联系管理员');
      }
    },
    /**
     * 上传的文件状态改变
     */
    uploadFileStateChange(file, fileList) {
      console.log('[uploadFileStateChange]:uploadFile', [file, fileList]);
    },
    /**
     * 已上传文件移除前事件
     */
    uploadFileBeforeRemove() {},
    /**
     * 移除已上传的文件
     */
    uploadFileRemove(file, fileList) {
      console.log('uploadFileRemove', [file, fileList]);
    },
    /**
     * 上传文件之前的钩子
     */
    uploadBeforeFile(file) {
      const vm = this;
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.'));
      const whiteList = vm.upload.accept.split(',');
      whiteList.forEach((item) => item.trim());
      console.log('upload file type:', fileSuffix);
      console.log('upload file type whiteList:', whiteList);
      if (!whiteList.includes(fileSuffix)) {
        vm.$message({
          type: 'error',
          message: `仅支持上传${whiteList.join(', ')}格式`,
        });
        return false;
      }
      const limitFileSize = vm.upload.maxFielSize_M;
      const isLtFileSize = file.size / 1024 / 1024 < limitFileSize;
      if (!isLtFileSize) {
        vm.$message({
          type: 'error',
          message: `上传的文件大小不能超过 ${limitFileSize}MB`,
        });
        return false;
      }
      console.log('即将上传的文件', vm.upload.fileList);
      return true;
    },
    /**
     * 文件超出个数限制时的钩子
     */
    uploadFileExceed() {
      const vm = this;
      vm.$message({
        type: 'warning',
        message: '仅支持上传1个excel文件，请先移除已上传的excel文件',
      });
    },
    /**
     * 文件上传成功时的钩子
     */
    uploadFileSuccess(response) {
      const vm = this;
      if (response.status === 'success') {
        const refUploadFile = vm.$refs[vm.refUploadFile];
        if (refUploadFile) {
          vm.$nextTick(() => {
            refUploadFile.clearFiles();
          });
        }
      } else {
        vm.$message({
          type: 'error',
          message: response.message,
        });
      }
    },
    /**
     * excel文件上传
     */
    async httpUpload(httpRequest) {
      const vm = this;
      const file = httpRequest.file;
      if (!file) {
        vm.$message.error('请先上传excel文件');
        return;
      }
      const formData = new FormData();
      formData.append('file', file);
      const res = await importBatchData(formData);
      if (res.status === 'success') {
        vm.$message.success('导入成功');
      } else {
        vm.$message.error(res.message);
      }
      vm.dialogClose();
    },
    handlerInputValueChange(conditionName) {
      const vm = this;
      if (vm.$route.query && vm.$route.query.hasOwnProperty(conditionName)) {
        delete vm.$route.query[conditionName];
      }
    },
    /**
     * 检索条件清空
     */
    handlerClear(conditionName) {
      const vm = this;
      if (vm.$route.query && vm.$route.query.hasOwnProperty(conditionName)) {
        delete vm.$route.query[conditionName];
      }
      vm.handlerQuery();
    },
    /**
     * 弹窗关闭
     */
    dialogClose() {
      const vm = this;
      vm.resetFormFields();
      vm.formDialogVisible = false;
      vm.handlerQuery();
    },
    /**
     * 根据ref获取dom元素
     */
    getRefDom(refName) {
      const vm = this;
      return vm.$refs[refName];
    },
    /**
     * 重置表单字段并清空非法校验
     */
    resetFormFields() {
      const vm = this;
      const elForm = vm.$refs[vm.refFormName];
      if (elForm) {
        elForm.clearValidate();
      }
      vm.form = JSON.parse(JSON.stringify(vm.defaultForm));
    },
    /**
     * 表格多选事件
     */
    rowSelectionChange(rows) {
      const vm = this;
      vm.rowsSelected = rows;
    },
    /**
     * 数据标准版本
     */
    handlerFeatureVersionManage(row) {
      const vm = this;
      vm.$router.push({
        path: `/data-standard/feature-version`,
        query: {
          businessType: row.businessType,
          featureCName: row.featureName,
          versionCName: row.featureVersion,
        },
      });
    },
    /**
     * 字段值域配置
     */
    handlerFieldDomainManage(row) {
      const vm = this;
      vm.$router.push({
        path: `/data-standard/fieldDomain`,
        query: {
          businessType: row.businessType,
          featureCName: row.featureName,
          versionCName: row.featureVersion,
          fieldAlias: row.alias,
        },
      });
    },
    /**
     * 图层清单
     */
    handlerLayerManage() {
      const vm = this;
      vm.$router.push({ path: `/data-layers` });
    },
    /**
     * 远程搜索要素信息
     */
    remoteGetVersionsOptions(keyword) {
      const vm = this;
      if (!keyword || !keyword.trim()) {
        vm.featureVersionOptions = [];
        return;
      }
      versionList({
        query: {
          page: 1,
          pageSize: 500,
        },
        data: {
          versionCName: keyword.trim(),
        },
      })
        .then((res) => {
          if (res.status === 'success') {
            vm.featureVersionOptions = res.data.items.map((item) => {
              const {
                id,
                versionName,
                versionCName,
                versionSerial,
                isLatestVersion,
                versionDesc,
                featureId,
                createTime,
                updateTime,
                isDeleted,
                featureName,
                featureCName,
                isGeometry,
                geometryType,
                businessType,
                updateMethod,
                updateRate,
                featureDesc,
              } = item;
              return {
                id: id,
                label: versionCName,
                value: id,
                versionName: versionName,
                versionCName: versionCName,
                versionSerial: versionSerial,
                featureId: featureId,
              };
            });
            vm.docStandardOptions = [];
            vm.form.docStandard = '';
          } else {
            vm.$message.error(res.message);
          }
        })
        .catch((err) => {
          throw err;
        });
    },
    /**
     * 版本改变，触发字段出处选项改版
     */
    handlerVersionChange(val) {
      const vm = this;
      const featureVersion = vm.featureVersionOptions.find((item) => item.value === val);
      if (!featureVersion) {
        vm.$message.error(`未匹配到该要素版本，请检查该版本:【id: ${val} 】是否已被删除`);
      }
      const versionCName = featureVersion.label;
      standardDocsList({
        query: {
          page: 1,
          pageSize: 1000000,
        },
        data: {
          versionCName: !versionCName ? null : versionCName.trim(),
        },
      })
        .then((res) => {
          if (res.status === 'success') {
            const {
              data: { items },
            } = res;
            vm.form.docStandard = '';
            vm.docStandardOptions = items.map((item) => {
              const { id, docName, filePath, docStandardType, docDesc } = item;
              return {
                label: docName,
                value: id,
                id: id,
                name: docName,
                standardType: docStandardType,
                path: filePath,
                desc: docDesc,
              };
            });
          } else {
            vm.$message({
              type: 'error',
              message: res.message,
            });
          }
        })
        .catch((err) => {
          throw err;
        });
    },
    /**
     * 转换 true/false 为 是/否
     */
    parseBool2Text(val) {
      return val ? '是' : '否';
    },
    /**
     * 转换 是/否 为 true/false
     */
    parseText2Bool(val) {
      return val === '是' ? true : false;
    },
    validateInputNum(rule, value, callback) {
      if (!/^\d+$/.test(value)) {
        callback(new Error('只能输入数字'));
      } else {
        callback();
      }
    },
    checkIFNum(key, val) {
      const vm = this;
      if (['', null].includes(val)) {
        return;
      }
      const isNum = val
        .split('')
        .every((c) => ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].includes(c));
      if (!isNum) {
        vm.$message.warning('只能输入数字');
        if (isNaN(parseInt(val))) {
          vm.form[key] = null;
          return;
        }
      }
      vm.form[key] = `${parseInt(val)}`;
    },
    runtimeSet(refNode, obj, propName, propValue) {
      refNode.$set(obj, propName, propValue);
    },
  },
};
</script>

<style lang="scss" scoped>
.feature-version__container {
  height: calc(100vh - 85px);
  overflow: hidden;
  background-color: #f2f2f2;
  .content {
    width: 100%;
    height: 100%;
    overflow: hidden;
    background-color: rgba(255, 255, 255, 1);
    padding: 15px;
    display: flex;
    flex: 1;
    flex-direction: column;
    .panel-header {
      height: 40px;
    }
    .panel-content {
      flex: 1;
      height: calc(100% - 80px);
      padding: 12px 0;
    }
    .panel-footer {
      height: 40px;
    }
  }

  .search-conditions {
    display: flex;
    flex-direction: column;
    font-size: small;
    .condition-item {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      .item-label {
        width: 206px;
        text-align: right;
        padding-right: 10px;
      }
      .item-value {
        flex: 1;
      }
    }
  }

  .search-func {
    padding: 0px 10px;
    .btn-query {
      display: inline-block;
      width: 50%;
      padding-right: 10px;
    }
    .btn-reset {
      display: inline-block;
      width: 50%;
      padding-left: 10px;
    }
  }

  .panel-header {
    .table-func {
      width: 28%;
      .table-func-btn {
        display: inline-block;
        padding: 0px 10px;
        width: 25%;
      }
      .btn-add {
        padding-left: 0px;
      }
    }
  }

  .panel-content {
    ::v-deep .table-head-cell-style {
      text-align: center !important;
      color: rgba(100, 100, 100);
    }
    ::v-deep .table-head-cell-style {
      color: rgb(0, 0, 0);
      background: rgb(215, 215, 215);
    }
  }

  .panel-footer {
    display: flex;
    align-items: flex-end;
  }

  .btn-action {
    width: 100%;
    .btn-modify {
      display: inline-block;
      width: 50%;
      padding: 0px 10px;
    }
    .btn-approval {
      display: inline-block;
      width: 50%;
      padding: 0px 10px;
    }
  }

  // 临时
  .table-panel {
    width: 100%;
    height: 100%;
    overflow: hidden;
    background-color: rgba(255, 255, 255, 1);
    // padding: 15px 10px;
  }

  .form-dialog {
    ::v-deep .el-dialog__header {
      text-align: center;
    }
    ::v-deep .el-dialog__body {
      padding: 20px !important;
      padding-top: 5px !important;
    }
    ::v-deep .normal-table-header-cell {
      color: rgb(0, 0, 0);
      background: rgb(215, 215, 215);
      font-weight: bold;
    }
  }

  ::v-deep .normal-table-header-cell {
    color: rgb(0, 0, 0);
    background: rgb(215, 215, 215);
    font-weight: bold;
  }

  .btn-list {
    .btn-item {
      display: inline-block;
      .el-button {
        // background: #169bd5;
        // border-color: #169bd5;
      }
    }
  }
  ::v-deep .header-search-button {
    // background: #169bd5;
    // border-color: #169bd5;
  }
  ::v-deep .col-btn-item {
    display: none;
  }
}

.form-dialog {
  .form-panel {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
  }
  .approval-list {
    flex: 1;
    display: flex;
    flex-direction: column;
    .approval-list-item {
      height: 40px;
      line-height: 40px;
      flex: 1;
      display: flex;
      .label {
        width: 13%;
        text-align: center;
      }
      .value {
        flex: 1;
      }
    }
    .permission-approval {
      height: 40px;
      line-height: 40px;
    }
  }
  .approval-action {
    height: 60px;
    line-height: 60px;
    text-align: center;
    .btn-submit {
      width: 150px;
      background: #169bd5;
      border-color: #169bd5;
    }
  }

  ::v-deep .el-dialog__body {
    padding-bottom: 10px;
  }
}

.filter-conditions {
  .filter-item {
    display: inline-block;
    .el-button {
      background: #169bd5;
      border-color: #169bd5;
    }
  }
}

.form-item {
  width: 100%;
}
</style>
